const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const bodyParser = require('body-parser');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const moneyUtils = require('./utils');

const app = express();
const port = 3000;
const JWT_SECRET = 'note-book-2025'; // 在实际生产环境中，应该使用环境变量存储

// 配置CORS - 允许所有域名访问
const corsOptions = {
  origin: '*', // 允许所有域名访问
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  credentials: false, // 当使用通配符时，credentials必须为false
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));
app.use(bodyParser.json());

// 使用cors中间件处理所有预检请求，不需要单独设置app.options

// 初始化数据库
const db = new sqlite3.Database('./data.db');
db.serialize(() => {
  // 创建用户表
  db.run(`CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    created_at TEXT,
    hkd_amount REAL DEFAULT 0,
    hkd_rate REAL DEFAULT 0.935
  )`);

  // 修改账户表，添加用户ID字段
  db.run(`CREATE TABLE IF NOT EXISTS accounts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    name TEXT NOT NULL,
    ali REAL DEFAULT 0,
    wx REAL DEFAULT 0,
    bank REAL DEFAULT 0,
    total REAL DEFAULT 0,
    FOREIGN KEY(user_id) REFERENCES users(id)
  )`);

  // 修改记录表，添加用户ID字段、删除标记字段和备注字段
  db.run(`CREATE TABLE IF NOT EXISTS records (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    account_id INTEGER,
    date TEXT,
    amount REAL,
    type TEXT,
    channel TEXT,
    remark TEXT,
    is_deleted INTEGER DEFAULT 0,
    FOREIGN KEY(user_id) REFERENCES users(id),
    FOREIGN KEY(account_id) REFERENCES accounts(id)
  )`);
  
  // 创建港币钱包金额记录表
  db.run(`CREATE TABLE IF NOT EXISTS amount_records (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    amount REAL NOT NULL,
    rate REAL NOT NULL,
    create_time TEXT NOT NULL,
    remark TEXT,
    FOREIGN KEY(user_id) REFERENCES users(id)
  )`);
  
  // 添加remark字段到records表（如果不存在）
  db.all(`PRAGMA table_info(records)`, (err, rows) => {
    if (err) {
      console.error('检查表结构失败:', err.message);
      return;
    }
    
    // 检查remark字段是否存在
    const hasRemark = rows && rows.some(row => row.name === 'remark');
    if (!hasRemark) {
      db.run(`ALTER TABLE records ADD COLUMN remark TEXT`, (err) => {
        if (err) {
          console.error('添加remark字段失败:', err.message);
        } else {
          console.log('成功添加remark字段到records表');
        }
      });
    }
    
    // 检查bank字段是否存在于accounts表
    db.all(`PRAGMA table_info(accounts)`, (err, rows) => {
      if (err) {
        console.error('检查accounts表结构失败:', err.message);
        return;
      }
      
      const hasBank = rows && rows.some(row => row.name === 'bank');
      if (!hasBank) {
        db.run(`ALTER TABLE accounts ADD COLUMN bank REAL DEFAULT 0`, (err) => {
          if (err) {
            console.error('添加bank字段失败:', err.message);
          } else {
            console.log('成功添加bank字段到accounts表');
          }
        });
      }
      
      // 检查credit_card字段是否存在于accounts表
      const hasCreditCard = rows && rows.some(row => row.name === 'credit_card');
      if (!hasCreditCard) {
        db.run(`ALTER TABLE accounts ADD COLUMN credit_card REAL DEFAULT 0`, (err) => {
          if (err) {
            console.error('添加credit_card字段失败:', err.message);
          } else {
            console.log('成功添加credit_card字段到accounts表');
          }
        });
      }
      
      // 检查港币相关字段是否存在于users表
      db.all(`PRAGMA table_info(users)`, (err, rows) => {
        if (err) {
          console.error('检查users表结构失败:', err.message);
          return;
        }
        
        const hasHkdAmount = rows && rows.some(row => row.name === 'hkd_amount');
        if (!hasHkdAmount) {
          db.run(`ALTER TABLE users ADD COLUMN hkd_amount REAL DEFAULT 0`, (err) => {
            if (err) {
              console.error('添加hkd_amount字段失败:', err.message);
            } else {
              console.log('成功添加hkd_amount字段到users表');
            }
          });
        }
        
        const hasHkdRate = rows && rows.some(row => row.name === 'hkd_rate');
        if (!hasHkdRate) {
          db.run(`ALTER TABLE users ADD COLUMN hkd_rate REAL DEFAULT 0.935`, (err) => {
            if (err) {
              console.error('添加hkd_rate字段失败:', err.message);
            } else {
              console.log('成功添加hkd_rate字段到users表');
            }
          });
        }
        
        // 检查昨日总额字段是否存在于users表
        const hasYesterdayAmount = rows && rows.some(row => row.name === 'yesterday_amount');
        if (!hasYesterdayAmount) {
          db.run(`ALTER TABLE users ADD COLUMN yesterday_amount REAL DEFAULT 0`, (err) => {
            if (err) {
              console.error('添加yesterday_amount字段失败:', err.message);
            } else {
              console.log('成功添加yesterday_amount字段到users表');
            }
          });
        }
      });
    });
  });
});

// 验证 Token 的中间件
const verifyToken = (req, res, next) => {
  // 获取Authorization头
  const authHeader = req.headers.authorization;
  
  // 从Authorization头中提取token
  let token = null;
  if (authHeader) {
    // 尝试提取Bearer token
    if (authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      // 如果没有Bearer前缀，直接使用整个值
      token = authHeader;
    }
  }
  
  if (!token) {
    return res.status(401).json({ error: '未提供令牌，请先登录' });
  }
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    return res.status(401).json({ error: '无效的令牌，请重新登录' });
  }
};

// 用户注册
app.post('/api/register', async (req, res) => {
  const { username, password } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({ error: '用户名和密码不能为空' });
  }
  
  try {
    // 检查用户是否已存在
    db.get('SELECT * FROM users WHERE username = ?', [username], async (err, user) => {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      
      if (user) {
        return res.status(400).json({ error: '用户名已存在' });
      }
      
      // 加密密码
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);
      const createdAt = new Date().toISOString();
      
      // 创建用户
      db.run('INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)', 
        [username, hashedPassword, createdAt], 
        function(err) {
          if (err) {
            return res.status(500).json({ error: err.message });
          }
          
          // 生成令牌
          const token = jwt.sign(
            { id: this.lastID, username },
            JWT_SECRET,
            { expiresIn: '7d' }
          );
          
          res.json({ token, user: { id: this.lastID, username } });
        }
      );
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 用户登录
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({ error: '用户名和密码不能为空' });
  }
  
  try {
    // 查找用户
    db.get('SELECT * FROM users WHERE username = ?', [username], async (err, user) => {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      
      if (!user) {
        return res.status(400).json({ error: '用户名或密码错误' });
      }
      
      // 验证密码
      const isMatch = await bcrypt.compare(password, user.password);
      
      if (!isMatch) {
        return res.status(400).json({ error: '用户名或密码错误' });
      }
      
      // 生成令牌
      const token = jwt.sign(
        { id: user.id, username: user.username },
        JWT_SECRET,
        { expiresIn: '7d' }
      );
      
      res.json({ token, user: { id: user.id, username: user.username } });
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取当前用户信息（包含港币钱包信息）
app.get('/api/user', verifyToken, (req, res) => {
  db.get('SELECT id, username, hkd_amount, hkd_rate, yesterday_amount FROM users WHERE id = ?', [req.user.id], (err, user) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!user) return res.status(404).json({ error: '用户不存在' });
    
    // 确保数据格式正确
    const hkdAmount = parseFloat((user.hkd_amount || 0).toFixed(2));
    const hkdRate = parseFloat((user.hkd_rate || 0.935).toFixed(3));
    const cnyCurrency = parseFloat((hkdAmount * hkdRate).toFixed(2));
    const yesterdayAmount = parseFloat((user.yesterday_amount || 0).toFixed(2));
    
    res.json({ 
      user: {
        id: user.id,
        username: user.username,
        yesterday_amount: yesterdayAmount,
        hkd_wallet: {
          amount: hkdAmount,
          rate: hkdRate,
          cny: cnyCurrency
        }
      } 
    });
  });
});

// 更新港币钱包金额
app.put('/api/user/hkd-amount', verifyToken, (req, res) => {
  const { amount } = req.body;
  
  if (amount === undefined || isNaN(parseFloat(amount))) {
    return res.status(400).json({ error: '无效的金额' });
  }
  
  // 格式化金额，确保精确计算
  const formattedAmount = moneyUtils.formatMoney(amount);
  
  // 获取当前用户信息
  db.get('SELECT hkd_amount, hkd_rate FROM users WHERE id = ?', [req.user.id], (err, user) => {
    if (err) return res.status(500).json({ error: err.message });
    
    // 更新用户表中的金额
    db.run('UPDATE users SET hkd_amount = ? WHERE id = ?', [formattedAmount, req.user.id], function(err) {
      if (err) return res.status(500).json({ error: err.message });
      
      // 记录金额变更
      const createTime = new Date().toISOString();
      const rate = user.hkd_rate || 0.935;
      const remark = `从 ${user.hkd_amount || 0} 修改为 ${formattedAmount}`;
      
      // 插入记录
      db.run('INSERT INTO amount_records (user_id, amount, rate, create_time, remark) VALUES (?, ?, ?, ?, ?)', 
        [req.user.id, formattedAmount, rate, createTime, remark], 
        function(err) {
          if (err) return res.status(500).json({ error: err.message });
          
          // 计算折合人民币
          const cny = moneyUtils.multiply(formattedAmount, rate);
          
          res.json({
            hkd_wallet: {
              amount: formattedAmount,
              rate: moneyUtils.formatMoney(rate, 3),
              cny: cny
            }
          });
        }
      );
    });
  });
});

// 更新港币汇率
app.put('/api/user/hkd-rate', verifyToken, (req, res) => {
  const { rate } = req.body;
  
  if (rate === undefined || isNaN(parseFloat(rate)) || parseFloat(rate) <= 0) {
    return res.status(400).json({ error: '无效的汇率' });
  }
  
  // 保留三位小数，汇率特殊处理
  const formattedRate = parseFloat(parseFloat(rate).toFixed(3));
  
  // 获取当前用户信息
  db.get('SELECT hkd_amount, hkd_rate FROM users WHERE id = ?', [req.user.id], (err, user) => {
    if (err) return res.status(500).json({ error: err.message });
    
    // 更新用户表中的汇率
    db.run('UPDATE users SET hkd_rate = ? WHERE id = ?', [formattedRate, req.user.id], function(err) {
      if (err) return res.status(500).json({ error: err.message });
      
      // 获取当前最新金额
      const currentAmount = user.hkd_amount || 0;
      
      // 记录汇率变更
      const createTime = new Date().toISOString();
      const remark = `汇率从 ${user.hkd_rate || 0.935} 修改为 ${formattedRate}`;
      
      // 插入记录
      db.run('INSERT INTO amount_records (user_id, amount, rate, create_time, remark) VALUES (?, ?, ?, ?, ?)', 
        [req.user.id, currentAmount, formattedRate, createTime, remark], 
        function(err) {
          if (err) return res.status(500).json({ error: err.message });
          
          // 计算折合人民币
          const cny = moneyUtils.multiply(currentAmount, formattedRate);
          
          res.json({
            hkd_wallet: {
              amount: moneyUtils.formatMoney(currentAmount),
              rate: moneyUtils.formatMoney(formattedRate, 3),
              cny: cny
            }
          });
        }
      );
    });
  });
});

// 更新昨日总额
app.put('/api/user/yesterday-amount', verifyToken, (req, res) => {
  const { amount } = req.body;
  
  if (amount === undefined || isNaN(parseFloat(amount))) {
    return res.status(400).json({ error: '无效的金额' });
  }
  
  // 格式化金额
  const formattedAmount = moneyUtils.formatMoney(amount);
  
  // 更新用户表中的昨日总额
  db.run('UPDATE users SET yesterday_amount = ? WHERE id = ?', [formattedAmount, req.user.id], function(err) {
    if (err) return res.status(500).json({ error: err.message });
    
    db.get('SELECT yesterday_amount FROM users WHERE id = ?', [req.user.id], (err, user) => {
      if (err) return res.status(500).json({ error: err.message });
      
      res.json({
        yesterday_amount: formattedAmount
      });
    });
  });
});

// 重置密码
app.put('/api/user/reset-password', verifyToken, async (req, res) => {
  const { oldPassword, newPassword } = req.body;
  
  if (!oldPassword || !newPassword) {
    return res.status(400).json({ error: '旧密码和新密码不能为空' });
  }
  
  if (newPassword.length < 6) {
    return res.status(400).json({ error: '新密码长度不能少于6位' });
  }
  
  try {
    // 查找用户
    db.get('SELECT * FROM users WHERE id = ?', [req.user.id], async (err, user) => {
      if (err) {
        return res.status(500).json({ error: err.message });
      }
      
      if (!user) {
        return res.status(404).json({ error: '用户不存在' });
      }
      
      // 验证旧密码
      const isMatch = await bcrypt.compare(oldPassword, user.password);
      
      if (!isMatch) {
        return res.status(400).json({ error: '旧密码错误' });
      }
      
      // 加密新密码
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(newPassword, salt);
      
      // 更新密码
      db.run('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, req.user.id], function(err) {
        if (err) {
          return res.status(500).json({ error: err.message });
        }
        
        res.json({ success: true, message: '密码重置成功' });
      });
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取账户列表 - 修改为用户隔离，支持查看指定用户
app.get('/api/accounts', (req, res) => {
  // 检查是否有userId参数
  if (req.query.userId) {
    // 直接使用userId参数查询
    const userId = req.query.userId;
    
    db.all('SELECT * FROM accounts WHERE user_id = ?', [userId], (err, rows) => {
    if (err) return res.status(500).json({ error: err.message });
    
    // 格式化所有金额字段
    const formattedRows = rows.map(row => {
      return {
        ...row,
        ali: moneyUtils.formatMoney(row.ali),
        wx: moneyUtils.formatMoney(row.wx),
        bank: moneyUtils.formatMoney(row.bank),
        credit_card: moneyUtils.formatMoney(row.credit_card),
        total: moneyUtils.formatMoney(row.total)
      };
    });
    
    res.json(formattedRows);
  });
  } else {
    // 没有userId参数，需要验证token
    const authHeader = req.headers.authorization;
    if (!authHeader) {
      return res.status(401).json({ error: '未提供令牌，请先登录' });
    }
    
    let token = null;
    if (authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      token = authHeader;
    }
    
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      // 使用token中的用户ID查询
      db.all('SELECT * FROM accounts WHERE user_id = ?', [decoded.id], (err, rows) => {
        if (err) return res.status(500).json({ error: err.message });
        
        // 格式化所有金额字段
        const formattedRows = rows.map(row => {
          return {
            ...row,
            ali: moneyUtils.formatMoney(row.ali),
            wx: moneyUtils.formatMoney(row.wx),
            bank: moneyUtils.formatMoney(row.bank),
            credit_card: moneyUtils.formatMoney(row.credit_card),
            total: moneyUtils.formatMoney(row.total)
          };
        });
        
        res.json(formattedRows);
      });
    } catch (error) {
      return res.status(401).json({ error: '无效的令牌，请重新登录' });
    }
  }
});

// 新增账户 - 修改为用户隔离
app.post('/api/accounts', verifyToken, (req, res) => {
  const { name, ali, wx, bank, credit_card, total } = req.body;
  db.run(
    'INSERT INTO accounts (user_id, name, ali, wx, bank, credit_card, total) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [req.user.id, name, ali || 0, wx || 0, bank || 0, credit_card || 0, total || 0],
    function (err) {
      if (err) return res.status(500).json({ error: err.message });
      res.json({ id: this.lastID });
    }
  );
});

// 获取账户详情 - 修改为用户隔离，支持查看指定用户
app.get('/api/accounts/:id', (req, res) => {
  // 检查是否有userId参数
  if (req.query.userId) {
    // 直接使用userId参数查询
    const userId = req.query.userId;
    
    db.get('SELECT * FROM accounts WHERE id = ? AND user_id = ?', [req.params.id, userId], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!row) return res.status(404).json({ error: '账户不存在或无权访问' });
    
    // 格式化所有金额字段
    const formattedRow = {
      ...row,
      ali: moneyUtils.formatMoney(row.ali),
      wx: moneyUtils.formatMoney(row.wx),
      bank: moneyUtils.formatMoney(row.bank),
      credit_card: moneyUtils.formatMoney(row.credit_card),
      total: moneyUtils.formatMoney(row.total)
    };
    
    res.json(formattedRow);
  });
  } else {
    // 没有userId参数，需要验证token
    const authHeader = req.headers.authorization;
    if (!authHeader) {
      return res.status(401).json({ error: '未提供令牌，请先登录' });
    }
    
    let token = null;
    if (authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      token = authHeader;
    }
    
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      // 使用token中的用户ID查询
      db.get('SELECT * FROM accounts WHERE id = ? AND user_id = ?', [req.params.id, decoded.id], (err, row) => {
        if (err) return res.status(500).json({ error: err.message });
        if (!row) return res.status(404).json({ error: '账户不存在或无权访问' });
        
        // 格式化所有金额字段
        const formattedRow = {
          ...row,
          ali: moneyUtils.formatMoney(row.ali),
          wx: moneyUtils.formatMoney(row.wx),
          bank: moneyUtils.formatMoney(row.bank),
          credit_card: moneyUtils.formatMoney(row.credit_card),
          total: moneyUtils.formatMoney(row.total)
        };
        
        res.json(formattedRow);
      });
    } catch (error) {
      return res.status(401).json({ error: '无效的令牌，请重新登录' });
    }
  }
});

// 获取账户流水 - 修改为用户隔离，支持查看指定用户
app.get('/api/accounts/:id/records', (req, res) => {
  // 检查是否有userId参数
  if (req.query.userId) {
    // 直接使用userId参数查询
    const userId = req.query.userId;
    
  db.all('SELECT * FROM records WHERE account_id = ? AND user_id = ? AND is_deleted = 0 ORDER BY date DESC', 
      [req.params.id, userId], (err, rows) => {
      if (err) return res.status(500).json({ error: err.message });
      
      // 格式化所有金额字段
      const formattedRows = rows.map(row => {
        return {
          ...row,
          amount: moneyUtils.formatMoney(row.amount)
        };
      });
      
      res.json(formattedRows);
      });
  } else {
    // 没有userId参数，需要验证token
    const authHeader = req.headers.authorization;
    if (!authHeader) {
      return res.status(401).json({ error: '未提供令牌，请先登录' });
    }
    
    let token = null;
    if (authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      token = authHeader;
    }
    
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      
      // 使用token中的用户ID查询
      db.all('SELECT * FROM records WHERE account_id = ? AND user_id = ? AND is_deleted = 0 ORDER BY date DESC', 
        [req.params.id, decoded.id], (err, rows) => {
          if (err) return res.status(500).json({ error: err.message });
          
          // 格式化所有金额字段
          const formattedRows = rows.map(row => {
            return {
              ...row,
              amount: moneyUtils.formatMoney(row.amount)
            };
          });
          
          res.json(formattedRows);
        });
    } catch (error) {
      return res.status(401).json({ error: '无效的令牌，请重新登录' });
    }
  }
});

// 新增API：根据用户ID查询账户状态（只读权限）
app.get('/api/user/:userId/status', (req, res) => {
  const userId = req.params.userId;
  
  // 查询用户信息
  db.get('SELECT id, username, hkd_amount, hkd_rate, yesterday_amount FROM users WHERE id = ?', [userId], (err, user) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!user) return res.status(404).json({ error: '用户不存在' });
    
    // 确保数据格式正确
    const hkdAmount = parseFloat((user.hkd_amount || 0).toFixed(2));
    const hkdRate = parseFloat((user.hkd_rate || 0.935).toFixed(3));
    const cnyCurrency = parseFloat((hkdAmount * hkdRate).toFixed(2));
    const yesterdayAmount = parseFloat((user.yesterday_amount || 0).toFixed(2));
    
    // 获取用户账户列表
    db.all('SELECT id, name, ali, wx, bank, credit_card, total FROM accounts WHERE user_id = ?', [userId], (err, accounts) => {
      if (err) return res.status(500).json({ error: err.message });
      
      // 格式化所有金额字段
      const formattedAccounts = accounts.map(account => {
        return {
          ...account,
          ali: moneyUtils.formatMoney(account.ali),
          wx: moneyUtils.formatMoney(account.wx),
          bank: moneyUtils.formatMoney(account.bank),
          credit_card: moneyUtils.formatMoney(account.credit_card),
          total: moneyUtils.formatMoney(account.total)
        };
      });
      
      // 获取账户总览数据
      db.get(`SELECT 
        SUM(CASE WHEN type = 'in' THEN amount ELSE 0 END) as totalIncome,
        SUM(CASE WHEN type = 'out' THEN amount ELSE 0 END) as totalExpense FROM records 
        WHERE user_id = ? AND is_deleted = 0`, [userId], (err, row) => {
          if (err) return res.status(500).json({ error: err.message });
          
          // 账户总额 = 所有记录的收入-支出
          const accountAmount = moneyUtils.subtract(row.totalIncome || 0, row.totalExpense || 0);
          
          // 总额 = 账户总额 + 港币钱包折合人民币
          const amount = moneyUtils.add(accountAmount, cnyCurrency);
          
          // 计算增长额（当前总额 - 昨日总额）
          const growthAmount = moneyUtils.subtract(amount, yesterdayAmount);
          
          // 返回只读数据
          res.json({
            user: {
              id: user.id,
              username: user.username
            },
            accountStatus: {
              amount: moneyUtils.formatMoney(amount),
              accountAmount: moneyUtils.formatMoney(accountAmount),
              yesterdayAmount: moneyUtils.formatMoney(yesterdayAmount),
              growthAmount: moneyUtils.formatMoney(growthAmount),
              hkdWallet: {
                amount: moneyUtils.formatMoney(hkdAmount),
                rate: moneyUtils.formatMoney(hkdRate, 3),
                cny: moneyUtils.formatMoney(cnyCurrency)
              }
            },
            accounts: formattedAccounts
          });
        });
    });
    });
});

// 新增/修改流水 - 修改为用户隔离
app.post('/api/records', verifyToken, (req, res) => {
  const { id, account_id, date, amount, type, channel, remark } = req.body;
  
  // 格式化金额，确保精确计算
  const formattedAmount = moneyUtils.formatMoney(amount);
  
  // 首先验证账户是否属于当前用户
  db.get('SELECT * FROM accounts WHERE id = ? AND user_id = ?', [account_id, req.user.id], (err, account) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!account) return res.status(404).json({ error: '账户不存在或无权访问' });
    
    db.run(
      'INSERT INTO records (user_id, account_id, date, amount, type, channel, remark) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [req.user.id, account_id, date, formattedAmount, type, channel, remark || ''],
      function (err) {
        if (err) return res.status(500).json({ error: err.message });
        // 更新账户余额
        db.run(`UPDATE accounts SET 
            ali = ali + CASE WHEN ? = 'in' AND ? = '支付宝' THEN ? 
                              WHEN ? = 'out' AND ? = '支付宝' THEN -? ELSE 0 END,
            wx = wx + CASE WHEN ? = 'in' AND ? = '微信' THEN ? 
                            WHEN ? = 'out' AND ? = '微信' THEN -? ELSE 0 END,
            bank = bank + CASE WHEN ? = 'in' AND ? = '银行卡' THEN ? 
                               WHEN ? = 'out' AND ? = '银行卡' THEN -? ELSE 0 END,
            credit_card = credit_card + CASE WHEN ? = 'in' AND ? = '信用卡' THEN ? 
                                             WHEN ? = 'out' AND ? = '信用卡' THEN -? ELSE 0 END,
            total = total + CASE WHEN ? = 'in' THEN ? ELSE -? END
            WHERE id = ? AND user_id = ?`,
            [
              // 支付宝部分参数
              type, channel, formattedAmount, 
              type, channel, formattedAmount,
              // 微信部分参数
              type, channel, formattedAmount,
              type, channel, formattedAmount,
              // 银行卡部分参数
              type, channel, formattedAmount,
              type, channel, formattedAmount,
              // 信用卡部分参数
              type, channel, formattedAmount,
              type, channel, formattedAmount,
              // 总额部分参数
              type, formattedAmount, formattedAmount,
              // WHERE条件参数
              account_id, req.user.id
            ],
        function (err) {
          if (err) return res.status(500).json({ error: err.message });
          res.json({ id: this.lastID });
        })
      }
    );
  });
});

// 删除账户 - 修改为用户隔离
app.delete('/api/accounts/:id', verifyToken, (req, res) => {
  const accountId = req.params.id;
  
  // 首先验证账户是否属于当前用户
  db.get('SELECT * FROM accounts WHERE id = ? AND user_id = ?', [accountId, req.user.id], (err, account) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!account) return res.status(404).json({ error: '账户不存在或无权访问' });
    
    // 开始事务
    db.serialize(() => {
      db.run('BEGIN TRANSACTION');
      
      // 1. 标记该账户下所有交易记录为已删除
      db.run('UPDATE records SET is_deleted = 1 WHERE account_id = ? AND user_id = ?', 
        [accountId, req.user.id], function(err) {
          if (err) {
            db.run('ROLLBACK');
            return res.status(500).json({ error: '删除关联交易记录失败: ' + err.message });
          }
          
          // 2. 删除账户
          db.run('DELETE FROM accounts WHERE id = ? AND user_id = ?', 
            [accountId, req.user.id], function(err) {
              if (err) {
                db.run('ROLLBACK');
                return res.status(500).json({ error: '删除账户失败: ' + err.message });
              }
              
              // 提交事务
              db.run('COMMIT', function(err) {
                if (err) {
                  db.run('ROLLBACK');
                  return res.status(500).json({ error: '提交事务失败: ' + err.message });
                }
                
                res.json({ success: true, message: '账户及其关联记录已成功删除' });
              });
            });
        });
    });
  });
});

// 获取单条流水 - 修改为用户隔离
app.get('/api/records/:id', verifyToken, (req, res) => {
  db.get('SELECT * FROM records WHERE id = ? AND user_id = ? AND is_deleted = 0', [req.params.id, req.user.id], (err, row) => {
    if (err) return res.status(500).json({ error: err.message });
    if (!row) return res.status(404).json({ error: '流水记录不存在或无权访问' });
    
    // 格式化金额
    const formattedRow = {
      ...row,
      amount: moneyUtils.formatMoney(row.amount)
    };
    
    res.json(formattedRow);
  });
});

// 删除流水记录（逻辑删除）- 修改为用户隔离
app.delete('/api/records/:id', verifyToken, (req, res) => {
  // 首先获取流水记录信息
  db.get('SELECT * FROM records WHERE id = ? AND user_id = ? AND is_deleted = 0', 
    [req.params.id, req.user.id], (err, record) => {
      if (err) return res.status(500).json({ error: err.message });
      if (!record) return res.status(404).json({ error: '流水记录不存在或无权访问' });
      
      // 标记为已删除
      db.run('UPDATE records SET is_deleted = 1 WHERE id = ? AND user_id = ?',
        [req.params.id, req.user.id], function(err) {
          if (err) return res.status(500).json({ error: err.message });
          
          // 反向更新账户余额
          db.run(`UPDATE accounts SET 
              ali = ali - CASE WHEN ? = 'in' AND ? = '支付宝' THEN ? 
                             WHEN ? = 'out' AND ? = '支付宝' THEN -? ELSE 0 END,
              wx = wx - CASE WHEN ? = 'in' AND ? = '微信' THEN ? 
                           WHEN ? = 'out' AND ? = '微信' THEN -? ELSE 0 END,
              bank = bank - CASE WHEN ? = 'in' AND ? = '银行卡' THEN ? 
                              WHEN ? = 'out' AND ? = '银行卡' THEN -? ELSE 0 END,
              credit_card = credit_card - CASE WHEN ? = 'in' AND ? = '信用卡' THEN ? 
                                               WHEN ? = 'out' AND ? = '信用卡' THEN -? ELSE 0 END,
              total = total - CASE WHEN ? = 'in' THEN ? ELSE -? END
              WHERE id = ? AND user_id = ?`,
              [
                // 支付宝部分参数
                record.type, record.channel, record.amount, 
                record.type, record.channel, record.amount,
                // 微信部分参数
                record.type, record.channel, record.amount,
                record.type, record.channel, record.amount,
                // 银行卡部分参数
                record.type, record.channel, record.amount,
                record.type, record.channel, record.amount,
                // 信用卡部分参数
                record.type, record.channel, record.amount,
                record.type, record.channel, record.amount,
                // 总额部分参数
                record.type, record.amount, record.amount,
                // WHERE条件参数
                record.account_id, req.user.id
              ],
          function (err) {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ success: true, message: '流水记录已删除' });
          });
      });
  });
});

// 首页总览统计 - 修改为用户隔离，支持查看指定用户
app.get('/api/overview', (req, res) => {
  // 检查是否有userId参数
  if (req.query.userId) {
    // 直接使用userId参数查询
    const userId = req.query.userId;
  const today = new Date().toISOString().slice(0, 10);
  
    // 获取用户信息、港币钱包信息和昨日总额
    db.get('SELECT id, username, hkd_amount, hkd_rate, yesterday_amount FROM users WHERE id = ?', [userId], (err, user) => {
    if (err) return res.status(500).json({ error: err.message });
      if (!user) return res.status(404).json({ error: '用户不存在' });
    
    // 计算港币折合人民币
      const hkdAmount = user?.hkd_amount || 0;
      const hkdRate = user?.hkd_rate || 0.935;
    const hkdCny = moneyUtils.multiply(hkdAmount, hkdRate);
    
    // 获取用户设置的昨日总额
      const yesterdayAmount = user?.yesterday_amount || 0;
    
    // 获取账户收支总额
    db.get(`SELECT 
      SUM(CASE WHEN type = 'in' THEN amount ELSE 0 END) as totalIncome,
      SUM(CASE WHEN type = 'out' THEN amount ELSE 0 END) as totalExpense FROM records 
        WHERE user_id = ? AND is_deleted = 0`, [userId], (err, row) => {
        if (err) return res.status(500).json({ error: err.message });
        
        // 获取今日交易详情
        db.all(
          `SELECT type, channel, SUM(amount) as sum FROM records 
          WHERE date LIKE ? AND user_id = ? AND is_deleted = 0 GROUP BY type, channel`,
            [today + '%', userId],
          (err, rows) => {
            if (err) return res.status(500).json({ error: err.message });
            
            const result = {
              income: 0,
              expense: 0,
              wxIncome: 0,
              aliIncome: 0,
              bankIncome: 0,
              creditCardIncome: 0,
              wxExpense: 0,
              aliExpense: 0,
              bankExpense: 0,
              creditCardExpense: 0
            };
            
            rows.forEach((row) => {
              if (row.type === 'in') {
                result.income = moneyUtils.add(result.income, row.sum);
                if (row.channel === '微信') result.wxIncome = moneyUtils.add(result.wxIncome, row.sum);
                if (row.channel === '支付宝') result.aliIncome = moneyUtils.add(result.aliIncome, row.sum);
                if (row.channel === '银行卡') result.bankIncome = moneyUtils.add(result.bankIncome, row.sum);
                if (row.channel === '信用卡') result.creditCardIncome = moneyUtils.add(result.creditCardIncome, row.sum);
              } else {
                result.expense = moneyUtils.add(result.expense, row.sum);
                if (row.channel === '微信') result.wxExpense = moneyUtils.add(result.wxExpense, row.sum);
                if (row.channel === '支付宝') result.aliExpense = moneyUtils.add(result.aliExpense, row.sum);
                if (row.channel === '银行卡') result.bankExpense = moneyUtils.add(result.bankExpense, row.sum);
                if (row.channel === '信用卡') result.creditCardExpense = moneyUtils.add(result.creditCardExpense, row.sum);
              }
            });
            
            // 账户总额 = 所有记录的收入-支出
            const accountAmount = moneyUtils.subtract(row.totalIncome || 0, row.totalExpense || 0);
            
            // 总额 = 账户总额 + 港币钱包折合人民币
            const amount = moneyUtils.add(accountAmount, hkdCny);
            
              // 重构返回结果，增加用户信息和港币钱包信息
            const overview = {
              ...result,
                amount: moneyUtils.formatMoney(amount),                  // 当前总额
                accountAmount: moneyUtils.formatMoney(accountAmount),    // 账户总额
                hkdCny: moneyUtils.formatMoney(hkdCny),                 // 钱包总额
                yesterdayAmount: moneyUtils.formatMoney(yesterdayAmount), // 昨日总额（用户设置的）
                user: {
                  id: user.id,
                  username: user.username
                },
                hkdWallet: {
                  amount: moneyUtils.formatMoney(hkdAmount),
                  rate: moneyUtils.formatMoney(hkdRate, 3),
                  cny: moneyUtils.formatMoney(hkdCny)
                }
            };
            
            res.json(overview);
          }
        );
      });
  });
  } else {
    // 没有userId参数，需要验证token
    const authHeader = req.headers.authorization;
    if (!authHeader) {
      return res.status(401).json({ error: '未提供令牌，请先登录' });
    }
    
    let token = null;
    if (authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    } else {
      token = authHeader;
    }
    
    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      const userId = decoded.id;
      const today = new Date().toISOString().slice(0, 10);
      
      // 获取用户信息、港币钱包信息和昨日总额
      db.get('SELECT id, username, hkd_amount, hkd_rate, yesterday_amount FROM users WHERE id = ?', [userId], (err, user) => {
        if (err) return res.status(500).json({ error: err.message });
        if (!user) return res.status(404).json({ error: '用户不存在' });
        
        // 计算港币折合人民币
        const hkdAmount = user?.hkd_amount || 0;
        const hkdRate = user?.hkd_rate || 0.935;
        const hkdCny = moneyUtils.multiply(hkdAmount, hkdRate);
        
        // 获取用户设置的昨日总额
        const yesterdayAmount = user?.yesterday_amount || 0;
        
        // 获取账户收支总额
        db.get(`SELECT 
          SUM(CASE WHEN type = 'in' THEN amount ELSE 0 END) as totalIncome,
          SUM(CASE WHEN type = 'out' THEN amount ELSE 0 END) as totalExpense FROM records 
          WHERE user_id = ? AND is_deleted = 0`, [userId], (err, row) => {
            if (err) return res.status(500).json({ error: err.message });
            
            // 获取今日交易详情
            db.all(
              `SELECT type, channel, SUM(amount) as sum FROM records 
              WHERE date LIKE ? AND user_id = ? AND is_deleted = 0 GROUP BY type, channel`,
              [today + '%', userId],
              (err, rows) => {
                if (err) return res.status(500).json({ error: err.message });
                
                const result = {
                  income: 0,
                  expense: 0,
                  wxIncome: 0,
                  aliIncome: 0,
                  bankIncome: 0,
                  creditCardIncome: 0,
                  wxExpense: 0,
                  aliExpense: 0,
                  bankExpense: 0,
                  creditCardExpense: 0
                };
                
                rows.forEach((row) => {
                  if (row.type === 'in') {
                    result.income = moneyUtils.add(result.income, row.sum);
                    if (row.channel === '微信') result.wxIncome = moneyUtils.add(result.wxIncome, row.sum);
                    if (row.channel === '支付宝') result.aliIncome = moneyUtils.add(result.aliIncome, row.sum);
                    if (row.channel === '银行卡') result.bankIncome = moneyUtils.add(result.bankIncome, row.sum);
                    if (row.channel === '信用卡') result.creditCardIncome = moneyUtils.add(result.creditCardIncome, row.sum);
                  } else {
                    result.expense = moneyUtils.add(result.expense, row.sum);
                    if (row.channel === '微信') result.wxExpense = moneyUtils.add(result.wxExpense, row.sum);
                    if (row.channel === '支付宝') result.aliExpense = moneyUtils.add(result.aliExpense, row.sum);
                    if (row.channel === '银行卡') result.bankExpense = moneyUtils.add(result.bankExpense, row.sum);
                    if (row.channel === '信用卡') result.creditCardExpense = moneyUtils.add(result.creditCardExpense, row.sum);
                  }
                });
                
                // 账户总额 = 所有记录的收入-支出
                const accountAmount = moneyUtils.subtract(row.totalIncome || 0, row.totalExpense || 0);
                
                // 总额 = 账户总额 + 港币钱包折合人民币
                const amount = moneyUtils.add(accountAmount, hkdCny);
                
                // 重构返回结果，增加用户信息和港币钱包信息
                const overview = {
                  ...result,
                  amount: moneyUtils.formatMoney(amount),                  // 当前总额
                  accountAmount: moneyUtils.formatMoney(accountAmount),    // 账户总额
                  hkdCny: moneyUtils.formatMoney(hkdCny),                 // 钱包总额
                  yesterdayAmount: moneyUtils.formatMoney(yesterdayAmount), // 昨日总额（用户设置的）
                  user: {
                    id: user.id,
                    username: user.username
                  },
                  hkdWallet: {
                    amount: moneyUtils.formatMoney(hkdAmount),
                    rate: moneyUtils.formatMoney(hkdRate, 3),
                    cny: moneyUtils.formatMoney(hkdCny)
                  }
                };
                
                res.json(overview);
              }
            );
          });
      });
    } catch (error) {
      return res.status(401).json({ error: '无效的令牌，请重新登录' });
    }
  }
});

app.listen(port, '0.0.0.0', () => {
  console.log(`Server running at http://localhost:${port}`);
  console.log(`Server also accessible via your IP address on port ${port}`);
}); 